package com.example.customizedgroupmessage;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MailTemplateBox extends Activity{
	ArrayList<Template> arrTemplate;
	DBHelper mHelper;
	SQLiteDatabase db;
	public static final int REQUEST_CODE_MAILTEMPLATEDETAIL=3002;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_template_box);
		
		//템플릿 배열 생성
		arrTemplate = new ArrayList<Template>();
		arrTemplate.clear();
		
		Template temp;
		String _id = null;
		String msg = null;
		String msgTitle= null;
		mHelper = new DBHelper(this);
		db = mHelper.getReadableDatabase();
		Cursor cursor;
		cursor = db.rawQuery("SELECT * FROM mailtemplate ORDER BY _id DESC", null);
		while (cursor.moveToNext()) {
			_id = cursor.getString(0);
			msgTitle=cursor.getString(1);
			msg = cursor.getString(2);
			
			temp =  new Template();
			temp.setId(_id);
			temp.setOriginalMsg(msg);
			temp.setTitle(msgTitle);
			arrTemplate.add(temp);
		}
		cursor.close();
		mHelper.close();
		
		
		//어댑터 준비
		TemplateAdapter myTemplateAdapter= new TemplateAdapter(this, arrTemplate);
		ListView myTemplateList;
	
		//어댑터연결
		myTemplateList =(ListView)findViewById(R.id.listSMSTemplate);
		myTemplateList.setAdapter(myTemplateAdapter);
		myTemplateList.setOnItemClickListener(mItemClickListener);
		
	}
	
AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			AlertDialog dialog = createDialogBox(position, id);
		    dialog.show();
			
		}
	};

	
AlertDialog createDialogBox(int position, long id){
		LayoutInflater li = LayoutInflater.from(this);
		View smsTemplateDetail = li.inflate(R.layout.mail_detail, null);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);	
	
		builder.setTitle(arrTemplate.get(position).getId());
		builder.setView(smsTemplateDetail);
		
		TextView txtMsgTitle = (TextView)smsTemplateDetail.findViewById(R.id.txtMsgTitle);
		TextView txtMsg = (TextView)smsTemplateDetail.findViewById(R.id.txtMsg);

		txtMsgTitle.setText(arrTemplate.get(position).getTitle());
		//txtMsg.setText(arrTemplate.get(position).getOriginalMsg());
		txtMsg.setText("");
		arrTemplate.get(position).analyzeMsg();

		for(int i =0; i < arrTemplate.get(position).analyzedMsg.length ; i++){
			if(arrTemplate.get(position).analyzedMsg[i].equals("#name")){
				Drawable d = getResources().getDrawable(R.drawable.name);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#status")){
				Drawable d = getResources().getDrawable(R.drawable.status);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#org")){
				Drawable d = getResources().getDrawable(R.drawable.org);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#custom")){
				Drawable d = getResources().getDrawable(R.drawable.custom);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else{
				txtMsg.append(arrTemplate.get(position).analyzedMsg[i]);
			}
		}
	    
		builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});

		AlertDialog dialog = builder.create();

		return dialog;
	}	
class TemplateAdapter extends BaseAdapter{
	LayoutInflater mInflater;
	ArrayList<Template> items;
	Context _context;
	SQLiteDatabase db;
	DBHelper mHelper;
	

	public TemplateAdapter(Context context, ArrayList<Template> contentListItem){
		mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		items = contentListItem;
		_context = context;
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return items.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int pos = position;
		int res =R.layout.mail_template_item;
		convertView =mInflater.inflate(res, parent, false);
		
		TextView date =(TextView)convertView.findViewById(R.id.textDate);
		date.setText(items.get(position).getId());
		
		TextView content =(TextView)convertView.findViewById(R.id.textContent);
		content.setText(items.get(position).getTitle());
			
		Button btnDel = (Button)convertView.findViewById(R.id.btnDel);
		btnDel.setFocusable(false);
		btnDel.setTag(position);
		
		
		btnDel.setOnClickListener(
				new Button.OnClickListener() {
					@Override
					public void onClick(View v) {  
						Builder builder = new AlertDialog.Builder(_context);
						builder.setMessage("삭제 하시겠습니까?");
						builder.setPositiveButton("취소", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {    
								dialog.cancel();
							}
						});
						builder.setNegativeButton("확인", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								mHelper = new DBHelper(_context);
								db = mHelper.getWritableDatabase();
								String id = items.get(pos).getId();

								db.execSQL("DELETE FROM mailtemplate WHERE _id = '" + id + "';");

								mHelper.close();

								items.remove(pos);  //리스트뷰에서 지워주면서
								notifyDataSetChanged(); // 리스트뷰 갱신
								Toast.makeText(_context, "삭제 되었습니다.", Toast.LENGTH_SHORT).show();
							}
						});
						builder.show();
					}
				}
				);
		
			
		return convertView;
	}

}

}	
	

